import {Restart} from '../other/restart.js'
import fetch from 'node-fetch'
import YAML from 'yaml'
import fs from 'fs'
// 仅在pm2启动时候生效
// 测试域名自行修改

const websites = [
  'https://www.4399.com',
  'https://www.baidu.com',
  'https://www.icourse163.org',
  'https://www.mi.com'
];
const cron ='0 * * * *'
const restartDelay = 10 * 60 * 1000;
// 新增配置项：Fetch 超时时间 (单位毫秒)
const fetchTimeout = 1000; // 默认 Fetch 超时时间设置为 5 秒

export class duanwangchongqi extends plugin {
    constructor() {
        super({
            name: "断网重启检测",
            event: "message",
            rule: [{reg: "^#?断网检测", fnc: "NetTest"}],
        });

        this.task = {
      name: '断网重启检测',
      cron: cron,
      fnc: () => {
        this.NetTest().then(r => logger.mark("掉线检测完成"));
      },
    };
    }


    async NetTest() {
  let timeoutCount = 0;

  const fetchWebsiteStatus = (website, timeout) => { // 新的 fetchWebsiteStatus 函数
    return new Promise(async (resolve, reject) => {
      const startTime = Date.now();
      let controller = new AbortController(); // 用于控制超时
      const timer = setTimeout(() => {
        controller.abort(); // 超时后取消 fetch 请求
        reject(new Error(`Fetch 请求超时 (${timeout}ms)`));
      }, timeout);

      try {
        const response = await fetch(website, {
          signal: controller.signal, // 关联 AbortController
          mode: 'no-cors' //  使用 no-cors 模式，避免 CORS 问题，只关注是否能连通
        });
        clearTimeout(timer); // 清除超时定时器
        const endTime = Date.now();
        const latency = endTime - startTime;

        if (response.ok) { // response.ok 表示状态码为 2xx (成功)
          console.log(`${website}: Online (HTTP ${response.status} 响应, 延迟: ${latency}ms)`);
          resolve({ alive: true, latency: latency, status: response.status });
        } else {
          console.log(`${website}: Offline (HTTP ${response.status} 错误, 延迟: ${latency}ms)`);
          resolve({ alive: false, latency: latency, status: response.status });
        }
      } catch (error) {
        clearTimeout(timer); // 清除超时定时器
        console.error(`Error fetching ${website}: ${error.message}`);
        reject(error);
      }
    });
  };


  for (const website of websites) {
    try {
      // 调用新的 fetchWebsiteStatus 函数，并传入 fetchTimeout 配置
      const result = await fetchWebsiteStatus(website, fetchTimeout);
      if (!result.alive) {
        timeoutCount++;
      }
    } catch (error) {
      timeoutCount++;
    }
    await new Promise(resolve => setTimeout(resolve, 2000)); // 保持网站之间的 1 秒延迟
  }

  if (timeoutCount >= 2) {
    console.log('Two or more websites timed out (HTTP Fetch检测). Exiting...'); // 更新日志信息
    setTimeout(async () => {
  console.log('Waiting 10 minutes complete. Executing restart command...');
  setTimeout(() => this.restart(), 2000) // 保持2秒后重启
  const ret = await Bot.exec("pnpm run restart");
  console.log(ret);
}, restartDelay); // 延迟 10 分钟后执行重启
    // let restart_port = YAML.parse(fs.readFileSync(`./config/config/bot.yaml`, `utf-8`))
    // restart_port = restart_port.restart_port || 27881
    // let result = await fetch(`http://localhost:${restart_port || 27881}/restart`)
    //喵的重启
    // setTimeout(() => this.restart(), 2000)
    // const ret = await Bot.exec("pnpm run restart");
    // console.log(ret);

    // try {
    //   const response = await fetch('http://localhost:27881/restart'); // 保留 /exit 调用，看是否需要
    //   if (response.ok) {
    //     console.log('Successfully called exit endpoint.');
    //   } else {
    //     console.error(`Failed to call exit endpoint: ${response.status}`);
    //   }
    // } catch (error) {
    //   console.error(`Error calling exit endpoint: ${error}`);
    // }
  }
}

    // 修改后的 restart 方法: 使用 Restart 类进行重启 (参考 update.js)
    restart() {
        console.log("执行 restart 方法... 尝试使用 Restart 类重启 (参考 update.js)"); // 更新日志信息
        // 使用 Restart 类进行重启 (参考 update.js)
        // try {
        //     const restartInstance = new Restart(this.e); // 创建 Restart 类的实例，并传递 this.e
        //     restartInstance.restart().then(r => console.log("重启ing")); // 调用 Restart 实例的 restart() 方法
        //     console.log('Successfully called Restart.restart() from duanwangchongqi.restart() (参考 update.js).'); // 添加成功日志
        // } catch (error) {
        //     console.error(`Error calling Restart.restart() from duanwangchongqi.restart() (参考 update.js): ${error}`); // 添加错误日志
        // }
    }


}
